<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{Wechat, User as Users, Shoplist, Goods, GoodsSpec, Cart, Address, Region, Order, OrderGoods, Collect, Payment};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{

    public function info()
    {
        $user = $this->request->user;
        $result = [
            'id' => $user['id'],
            'code' => $user['code'],
            'nickName' => $user['nickName'],
            'gender' => $user['gender'],
            'avatarUrl' => $user['avatarUrl'],
            'mobile' => $user['mobile'],
            'collect' => (new Collect())->where('user_id', $user['id'])->count(),
            'money' => 0,
            'coupn' => 0
        ];
        $this->result($result, 0, '获取成功');
    }

    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
        ], [
            'code.require' => '微信授权码不能为空',
            'iv.require' => 'IV数据不能为空',
            'encryptedData.require' => 'encryptedData数据不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $data['shopid'] = $data['shopid'] ?? 0;
        $data['pid'] = $data['pid'] ?? 0;
        $model = new Users();
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        try {
            $res = $app->auth->session($data['code']);
        } catch (\Exception $e) {
            $this->result([], 1, '信息错误');
        }
        $time = $config['tokenExpireHours'];
        if (empty($res['session_key']) || empty($res['unionid']) || empty($res['openid'])) {
            $this->result([], 1, '登录失败,请重试');
        }
        //判断用户是否已经注册
        $user = $model->where('unionid', $res['unionid'])->find();
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        if ($data['pid']) {
            $pid = $model->where('code', $data['pid'])->value('id') ?? 0;
        }
        $save = [
            'unionid' => $res['unionid'],
            'session_key' => $res['session_key'],
            'openid' => $res['openid'],
            'shopid' => $data['shopid'] ?? 0,
            'pid' => $pid ?? 0,
            'gender' => $decryptedData['gender'] ?? 0,
            'province' => $decryptedData['province'] ?? '',
            'city' => $decryptedData['city'] ?? '',
            'avatarUrl' => $decryptedData['avatarUrl'] ?? '',
            'country' => $decryptedData['country'] ?? '',
            'nickName' =>  $decryptedData['nickName'] ?? '',
        ];
        if ($user) {
            if ($user['pid'] > 0) {
                unset($save['pid']);
            }
            if ($user['shopid'] > 0) {
                unset($save['shopid']);
            }
            $res2 = (new Users())->allowfield(true)->save($save, ['id' => $user['id']]);
        } else {
            $save['code'] = recode($model);
            $res2 = (new Users())->allowfield(true)->save($save);
            $user = (new Users())->where('unionid', $res['unionid'])->find();
        }
        if ($res2 && !empty($user)) {
            Redis::setex($res['session_key'], $time, $user['id']);
            $this->result(['token' => $res['session_key']], 0, '登录成功');
        }

        $this->result([], 1, '登录失败');
    }

    public function getshopid()
    {
        $user = $this->request->user;
        $model = new Shoplist;
        $result = [];
        if ($user && $user['shopid'] > 0) {
            $result = $model->where('id', $user['shopid'])->where('status', 1)->find();
        }
        $shopid  = $this->request->get('shopid/d', '0');
        if ($user['shopid'] == 0 && !empty($shopid)) {
            $result = $model->where('id', $shopid)->where('status', 1)->find();
        }
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        //获取附近的商家
        if (!$result) {
            Log::write(['lon' => $lon, 'lat' => $lat], 'weizhi');
            $filed = 'ROUND(6371.004*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
            $result = $model->field('id,title,ranges,lon,lat,' . $filed)
                ->order('dist asc')
                ->where('status', 1)
                ->find();
        }
        $result['r_status'] = 1;
        $result['km'] = 0;
        if ($result) {
            $km = getDistance($lon, $lat, $result['lon'], $result['lat']);
            $result['km'] = $km;
            if ($km > $result['ranges']) {
                $result['r_status'] = 2;
            }
        }
        $this->result($result, 0, '获取成功');
    }

    public function collect()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'goodsid' => 'require',
                'specid' => 'require',
            ], [
                'goodsid.require' => '商品ID不能为空',
                'specid.require' => '规格ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            //先查询商品数量 是否足够
            $specmodel = new GoodsSpec();
            $collectmodel = new Collect();
            $goodmodel = new Goods();
            //查询是否已经收藏过
            $collect = $collectmodel->where(['user_id' => $user['id'], 'goodsid' => $data['goodsid'], 'specid' => $data['specid']])->find();
            if (!empty($collect)) {
                $res = $collectmodel->where('id', $collect['id'])->delete();
                if ($res) {
                    $this->result([], 0, '取消收藏成功');
                }
                $this->result([], 1, '取消收藏失败，请重试');
            }
            //查询商品 是否还在线
            $goods = $goodmodel->where(['id' => $data['goodsid'], 'isSale' => 1, 'isdel' => 1])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            //查询商品规格
            $Spec = $specmodel->where(['goodid' => $data['goodsid'], 'id' => $data['specid'], 'isdel' => 1])->find();
            //规格为空删除
            if (empty($Spec)) {
                $this->result([], 1, '商品规格已下架');
            }
            $res = $collectmodel->allowfield(true)->save([
                'user_id' => $user['id'],
                'shopid' => $goods['shopid'],
                'images' => $goods['images'],
                'descs' => $goods['descs'],
                'specid' => $data['specid'],
                'goodsid' => $data['goodsid'],
                'title' => $goods['title'],
                'spectitle' => $Spec['name']
            ]);
            if ($res) {
                $this->result([], 0, '收藏成功');
            }
            $this->result([], 1, '收藏失败，请重试');
        } else {
            $user = $this->request->user;
            $collectmodel = new Collect();
            $specmodel = new GoodsSpec();
            $result = $collectmodel->where('user_id', $user['id'])->field('user_id,created', true)->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($result as $results) {
                $results['images'] = json_decode($results['images'], true) ?? [];
                $results['spec'] = $specmodel->where('id', $results['specid'])->where('isdel', 1)->field('price,oprice')->find();
                $results['price'] = $results['spec']['price'] ?? 0;
                $results['oprice'] = $results['spec']['oprice'] ?? 0;
                unset($results['spec']);
            }
            $this->result($result, 0, '获取成功');
        }
    }

    public function cart()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'goodsid' => 'require',
                'specid' => 'require',
                'number' => 'require',
            ], [
                'goodsid.require' => '商品ID不能为空',
                'specid.require' => '规格ID不能为空',
                'number.require' => '数量不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            //先查询商品数量 是否足够
            $specmodel = new GoodsSpec();
            $cartmodel = new Cart();
            $goodmodel = new Goods();
            $Spec = $specmodel->where(['goodid' => $data['goodsid'], 'id' => $data['specid'], 'isdel' => 1])->find();
            //查询是否已经加入过购物车
            if (!empty($data['cart'])) {
                $mycart = $cartmodel->where(['user_id' => $user['id'], 'id' => $data['cart']])->find();
                if (empty($mycart)) {
                    $this->result([], 1, '购物车ID错误');
                }
                if ($mycart['goodsid'] != $data['goodsid']) {
                    $data['goodsid'] = $mycart['goodsid'];
                }
            } else {
                $mycart = $cartmodel->where(['user_id' => $user['id'], 'specid' => $data['specid'], 'goodsid' => $data['goodsid']])->find();
            }
            //规格为空删除
            if (empty($Spec)) {
                if (!empty($mycart)) {
                    $res = $cartmodel->where('id', $mycart['id'])->delete();
                    if ($res) {
                        $this->result([], 1, '商品规格已下架');
                    }
                }
                $this->result([], 1, '商品规格已下架');
            }
            $number = 0;
            if (!empty($mycart)) {
                $number = $mycart['number'] + $data['number'];
            } else {
                $number = $data['number'];
            }
            if ($Spec['goodsstock'] < $number && $number > 0) {
                $this->result([], 1, '商品库存不足，剩余库存' . $Spec['goodsstock']);
            }
            //查询商品 是否还在线
            $goods = $goodmodel->where(['id' => $data['goodsid'], 'isSale' => 1, 'isdel' => 1])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            if (!empty($mycart)) {
                if ($number <= 0) {
                    $res = $cartmodel->where('id', $mycart['id'])->delete();
                } else {
                    $res = $cartmodel->where('id', $mycart['id'])
                        ->update(['specid' => $data['specid'], 'number' => $number, 'title' => $goods['title'], 'spectitle' => $Spec['name']]);
                }
            } else {
                if ($number <= 0) {
                    $this->result([], 1, '加入购物车数量必须大于0');
                }
                $res = $cartmodel->save([
                    'user_id' => $user['id'],
                    'shopid' => $goods['shopid'],
                    'specid' => $data['specid'],
                    'goodsid' => $data['goodsid'],
                    'number' => $number,
                    'title' => $goods['title'],
                    'spectitle' => $Spec['name']
                ]);
                $mycart = $cartmodel->where(['user_id' => $user['id'], 'shopid' => $goods['shopid'], 'specid' => $data['specid'], 'goodsid' => $data['goodsid']])->find();
            }
            if ($res) {
                $this->result(['id' => $mycart['id']], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $user = $this->request->user;
            $specmodel = new GoodsSpec();
            $cartmodel = new Cart();
            $goodmodel = new Goods();
            $shopmodel = new Shoplist();
            $list = [];
            $result = $cartmodel->where('user_id', $user['id'])->field('id,goodsid,specid,number,shopid')->select();
            foreach ($result as $results) {
                $status = 1;
                //查询商品信息
                $goods = $goodmodel->where(['isSale' => 1, 'isdel' => 1, 'id' => $results['goodsid']])
                    ->field('title,images')->find();
                $specs = $specmodel->where('goodid', $results['goodsid'])->where('isdel', 1)->field('id,name,goodid,price,oprice,goodsstock')->select();
                foreach ($specs as $spec) {
                    if ($spec['id'] == $results['specid']) {
                        $goods['price'] = $spec['price'];
                        $goods['total'] = $spec['price'] * $results['number'];
                        $goods['spectitle'] = $spec['name'];
                        $goods['cartid'] = $results['id'];
                        $goods['goodsid'] = $spec['goodid'];
                        $goods['specid'] = $results['specid'];
                        $status = 2;
                    }
                }
                if ($status == 2 && $results['number'] > 0 && $goods) {
                    $list[$results['shopid']]['name'] = $shopmodel->where('id', $results['shopid'])->value('title') ?? 0;
                    $goods['number'] = $results['number'];
                    $goods['images'] = json_decode($goods['images'], true) ?? [];
                    $goods['spec'] = $specs;
                    $list[$results['shopid']]['result'][] = $goods;
                }
                if ($status == 1 || $results['number'] <= 0) {
                    $cartmodel->where('id', $results['id'])->delete();
                }
            }
            $list = array_values($list);
            $this->result($list, 0, '获取成功');
        }
    }


    public function address()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'area' => 'require',
                'address' => 'require',
                'is_default' => 'require|in:1,2',
                'getaddress' => 'require',
                'lat' => 'require',
                'lon' => 'require',
            ], [
                'name.require' => '联系人姓名不能为空',
                'mobile.require' => '联系人电话不能为空',
                'area.require' => '区域ID不能为空',
                'address.require' => '具体地址不能为空',
                'getaddress.require' => '定位地址不能为空',
                'is_default.require' => '默认类型不能为空',
                'is_default.in' => '默认类型不正确',
                'lat.require' => '经度不能为空',
                'lon.require' => '纬度不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $regionmodel = new Region();
            $area = $regionmodel->where(['area_code' => $data['area'], 'level' => 3])->find();
            if (!$area) {
                $this->result([], 1, '区域编码出错');
            }
            $city = $regionmodel->where(['id' => $area['parent_id'], 'level' => 2])->find();
            if (!$city) {
                $this->result([], 1, '城市编码出错');
            }
            $province = $regionmodel->where(['id' => $city['parent_id'], 'level' => 1])->find();
            if (!$province) {
                $this->result([], 1, '省份编码出错');
            }
            $data['city'] = $city['area_code'];
            $data['province'] = $province['area_code'];
            $data['user_id'] = $this->request->user_id;
            $addressmodel = new Address();
            if ($data['is_default'] == 2) {
                $addressmodel->where(['user_id' => $data['user_id'], 'is_default' => 2])->update(['is_default' => 1]);
            }
            if (!empty($data['id'])) {
                $res = $addressmodel->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $addressmodel->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $addressmodel = new Address();
            $regionmodel = new Region();
            $result = $addressmodel->where('user_id', $this->request->user_id)->order('is_default desc')->field('user_id,created', true)->select();
            foreach ($result as $results) {
                $results['province_name'] = $regionmodel->where(['area_code' => $results['province'], 'level' => 1])->value('name');
                $results['city_name'] = $regionmodel->where(['area_code' => $results['city'], 'level' => 2])->value('name');
                $results['area_name'] = $regionmodel->where(['area_code' => $results['area'], 'level' => 3])->value('name');
            }
            $this->result($result, 0, '操作成功');
        }
    }

    public function address_del()
    {
        $id = $this->request->post('id/d', 0);
        $addressmodel = new Address();
        $result = $addressmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }


    public function reorder()
    {
        $id = $this->request->post('id/d', 0);
        //查询订单
        $shopmodel = new Shoplist();
        $ordermodel = new Order();
        $ordergoodsmodel = new OrderGoods();
        $specmodel = new GoodsSpec();
        $goodmodel = new Goods();
        $orders = $ordermodel->where('id', $id)->find();
        if (empty($orders)) {
            $this->result([], 1, '订单不存在');
        }
        $ordergoods = $ordergoodsmodel->where('ordersn', $orders['ordersn'])->select();
        if (count($ordergoods) <= 0) {
            $this->result([], 1, '订单不存在商品');
        }
        $order = [
            'ordersn' => reOrdercode($ordermodel),
            'user_id' => $this->request->user_id,
            'shopid' => $orders['shopid'],
            'name' => $orders['name'],
            'mobile' => $orders['mobile'],
            'province' => $orders['province'],
            'city' => $orders['city'],
            'area' => $orders['area'],
            'address' => $orders['address'],
            'lat' => $orders['lat'],
            'lon' => $orders['lon'],
            'ispay' => 1,
            'status' => 1,
            'total' => 0,
            'dates' => date('Y-m-d'),
            'payment' => 0
        ];
        $ordergoods2 = [];
        //查询商品库存和上下架
        foreach ($ordergoods as $ordergood) {
            $goods = $goodmodel->where(['id' => $ordergood['goodsid'], 'isSale' => 1, 'isdel' => 1])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品' . $ordergood['title'] . '已经下架');
            }
            $Spec = $specmodel->where(['goodid' => $ordergood['goodsid'], 'id' => $ordergood['specid'], 'isdel' => 1])->find();
            if (empty($Spec)) {
                $this->result([], 1, $ordergood['title'] . $ordergood['specname'] . '规格已下架');
            }
            if ($Spec['goodsstock'] < $ordergood['number']) {
                $this->result([], 1, $ordergood['title'] . $ordergood['specname'] . '库存数量不足' . $ordergood['number']);
            }
            $order['total'] += $ordergood['number'] * $Spec['price'];
            $ordergoods2[] = [
                'ordersn' => $order['ordersn'],
                'shopid' => $order['shopid'],
                'goodsid' => $goods['id'],
                'specid' => $Spec['id'],
                'title' => $goods['title'],
                'images' => $goods['images'],
                'specname' => $Spec['name'],
                'number' => $ordergood['number'],
                'price' => $Spec['price'],
                'total' => $ordergood['number'] * $Spec['price']
            ];
        }
        //查找店铺信息
        $shop = $shopmodel->where('id', $orders['shopid'])->find();
        if (empty($shop) || $shop['status'] != 1) {
            $this->result([], 1, '商户不存在');
        }
        if ($shop['status'] != 1) {
            $this->result([], 1, '商户已下架');
        }
        //计算俩点之间的距离是否超出商户配送范围
        $km = getDistance($shop['lon'], $shop['lat'], $order['lon'], $order['lat']);
        if ($shop['ranges'] != 0 && $km > $shop['ranges']) {
            $this->result([], 1, '配送地址超出商家配送范围');
        }
        if ($shop['startsend'] > $order['total']) {
            $this->result([], 1, '该商家' . $shop['startsend'] . '元起送');
        }
        if ($order['total'] == 0) {
            $order['ispay'] = 2;
            $order['status'] = 2;
            $order['payment'] = 1;
        }
        Db::startTrans();
        try {
            $ordermodel->allowfield(true)->save($order);
            $ordergoodsmodel->allowfield(true)->saveAll($ordergoods2);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            dump($e->getMessage());
            $this->result([], 1, '下单失败');
        }
        $order = $ordermodel->where(['ordersn' => $order['ordersn']])->value('id');
        $this->result(['ordersn' => $order['ordersn'], 'id' => $order], 0, '下单成功');
    }

    public function CreatedOrder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'cart' => 'require',
            'address' => 'require'
        ], [
            'cart.require' => '购物车数据不能为空',
            'address.require' => '收货订单ID不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $cart = json_decode($data['cart'], true) ?? [];
        if (count($cart) == 0) {
            $this->result([], 1, '购物车参数错误');
        }
        $shopmodel = new Shoplist();
        $cartmodel = new Cart();
        $ordermodel = new Order();
        $ordergoodsmodel = new OrderGoods();
        $specmodel = new GoodsSpec();
        $goodmodel = new Goods();
        $addressmodel = new Address();
        $myaddress = $addressmodel->where(['id' => $data['address'], 'user_id' => $this->request->user_id])->find();
        if (empty($myaddress)) {
            $this->result([], 1, '收货地址错误');
        }
        $mycart = $cartmodel->where(['id' => $cart, 'user_id' => $this->request->user_id])->select();
        if (count($mycart) == 0) {
            $this->result([], 1, '购物车参数错误');
        }
        $order = [
            'ordersn' => reOrdercode($ordermodel),
            'user_id' => $this->request->user_id,
            'shopid' => 0,
            'name' => $myaddress['name'],
            'mobile' => $myaddress['mobile'],
            'province' => $myaddress['province'],
            'city' => $myaddress['city'],
            'area' => $myaddress['area'],
            'address' => $myaddress['address'],
            'lat' => $myaddress['lat'],
            'lon' => $myaddress['lon'],
            'ispay' => 1,
            'status' => 1,
            'total' => 0,
            'dates' => date('Y-m-d'),
            'payment' => 0
        ];
        $ordergoods = [];
        //判断是否是同一商家的商品
        foreach ($mycart as $mycarts) {
            if ($order['shopid'] == 0) {
                $order['shopid'] = $mycarts['shopid'];
            }
            if ($order['shopid'] != $mycarts['shopid']) {
                $this->result([], 1, '暂不支持同时下多个店铺的订单');
            }
            $goods = $goodmodel->where(['id' => $mycarts['goodsid'], 'isSale' => 1, 'isdel' => 1])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品' . $mycarts['title'] . '已经下架');
            }
            $Spec = $specmodel->where(['goodid' => $mycarts['goodsid'], 'id' => $mycarts['specid'], 'isdel' => 1])->find();
            if (empty($Spec)) {
                $this->result([], 1, $mycarts['title'] . $mycarts['spectitle'] . '规格已下架');
            }
            if ($Spec['goodsstock'] < $mycarts['number']) {
                $this->result([], 1, $mycarts['title'] . $mycarts['spectitle'] . '库存数量不足' . $mycarts['number']);
            }
            $order['total'] += $mycarts['number'] * $Spec['price'];
            $ordergoods[] = [
                'ordersn' => $order['ordersn'],
                'shopid' => $order['shopid'],
                'goodsid' => $goods['id'],
                'specid' => $Spec['id'],
                'title' => $goods['title'],
                'images' => $goods['images'],
                'specname' => $Spec['name'],
                'number' => $mycarts['number'],
                'price' => $Spec['price'],
                'total' => $mycarts['number'] * $Spec['price']
            ];
        }
        //查找店铺信息
        $shop = $shopmodel->where('id', $order['shopid'])->find();
        if (empty($shop)) {
            $this->result([], 1, '商户不存在');
        }
        if ($shop['status'] != 1) {
            $this->result([], 1, '商户已下架');
        }
        //计算俩点之间的距离是否超出商户配送范围
        $km = getDistance($shop['lon'], $shop['lat'], $myaddress['lon'], $myaddress['lat']);
        if ($shop['ranges'] != 0 && $km > $shop['ranges']) {
            $this->result([], 1, '超出商家配送范围');
        }
        if ($shop['startsend'] > $order['total']) {
            $this->result([], 1, '该商家' . $shop['startsend'] . '元起送');
        }
        Db::startTrans();
        try {
            $ordermodel->allowfield(true)->save($order);
            $ordergoodsmodel->allowfield(true)->saveAll($ordergoods);
            $cartmodel->where(['id' => $cart, 'user_id' => $this->request->user_id])->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '下单失败');
        }
        $this->result(['ordersn' => $order['ordersn']], 0, '下单成功');
    }

    public function Order()
    {
        $ordermodel = new Order();
        $ordergoodsmodel = new OrderGoods();
        $status  = $this->request->get('status/d', 0);
        $result = $ordermodel->where(['user_id' => $this->request->user_id])->order('id desc')->field('id,ordersn,created,status,total,ispay,payment,rece');
        switch ($status) {
            case '1':
                $result = $result->where('status', $status);
                break;
            case '2':
                $result = $result->where('status', $status);
                break;
            case '3':
                $result = $result->where('status', $status);
                break;
            case '4':
                $result = $result->where('status', $status);
                break;
            case '5':
                $result = $result->where('status', $status);
                break;
            default:
                $result = $result;
                break;
        }
        $result = $result->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['times'] = 0;
            if (strtotime($results['created']) <= time()) {
                $results['times'] = strtotime($results['created']) + 10 * 60;
            }
            $results['status_text'] = '';
            $results['payment_text'] = '';
            if ($results['payment'] == 1) {
                $results['payment_text'] = '货到支付';
            } else {
                $results['payment_text'] = '微信支付';
            }
            switch ($results['status']) {
                case '1':
                    $results['status_text'] = '待付款';
                    break;
                case '2':
                    $results['status_text'] = '待配送';
                    break;
                case '3':
                    $results['status_text'] = '待收货';
                    break;
                case '4':
                    $results['status_text'] = '已完成';
                    break;
                case '5':
                    $results['status_text'] = '已取消';
                    break;
                default:
                    break;
            }
            if ($results['rece'] == 2) {
                $results['status_text'] = $results['status_text'] . '[售后中]';
            }
            $results['goods'] = $ordergoodsmodel->where('ordersn', $results['ordersn'])->field('title,images,specname,number,price')->select();
            foreach ($results['goods'] as $goods) {
                $goods['images'] = json_decode($goods['images'], true) ?? [];
            }
        }
        $this->result($result, 0, '获取成功');
    }

    public function Orderdetail()
    {
        $ordermodel = new Order();
        $ordergoodsmodel = new OrderGoods();
        $regionmodel = new Region();
        $id  = $this->request->get('id/d', 0);
        $result = $ordermodel->where(['user_id' => $this->request->user_id, 'id' => $id])
            ->field('id,ordersn,created,status,total,ispay,payment,name,mobile,province,city,area,address,lat,lon,rece,created')
            ->find();
        if ($result) {
            $result['times'] = 0;
            if (strtotime($result['created']) <= time()) {
                $result['times'] = strtotime($result['created']) + 10 * 60;
            }
            $result['province_text'] = $regionmodel->where(['area_code' => $result['province'], 'level' => 1])->value('name');
            $result['city_text'] = $regionmodel->where(['area_code' => $result['city'], 'level' => 2])->value('name');
            $result['area_text'] = $regionmodel->where(['area_code' => $result['area'], 'level' => 3])->value('name');
            $result['status_text'] = '';
            $result['payment_text'] = '';
            if ($result['payment'] == 1) {
                $result['payment_text'] = '货到支付';
            } else {
                $result['payment_text'] = '微信支付';
            }
            switch ($result['status']) {
                case '1':
                    $result['status_text'] = '待付款';
                    break;
                case '2':
                    $result['status_text'] = '待配送';
                    break;
                case '3':
                    $result['status_text'] = '待收货';
                    break;
                case '4':
                    $result['status_text'] = '已完成';
                    break;
                case '5':
                    $result['status_text'] = '已取消';
                    break;
                default:
                    break;
            }
            if ($result['rece'] == 2) {
                $result['status_text'] = $result['status_text'] . '[售后中]';
            }
            $result['goods'] = $ordergoodsmodel->where('ordersn', $result['ordersn'])->field('title,images,specname,number,price')->select();
            foreach ($result['goods'] as $goods) {
                $goods['images'] = json_decode($goods['images'], true) ?? [];
            }
        }
        $this->result($result, 0, '获取成功');
    }

    public function Ordercacel()
    {
        $ordermodel = new Order();
        $id  = $this->request->post('id/d', 0);
        $result = $ordermodel->where(['user_id' => $this->request->user_id, 'id' => $id])
            ->find();
        if (!$result) {
            $this->result([], 1, '订单不存在');
        }
        if ($result['rece'] == 2) {
            $this->result([], 1, '订单已处于售后状态');
        }
        switch ($result['status']) {
            case '1':
                //未付款订单直接取消
                $res = $ordermodel->where('id', $result['id'])->update(['status' => 5]);
                if ($res) {
                    $this->result([], 0, '订单已取消');
                }
                $this->result([], 1, '订单取消失败，请重试');
                break;
            case '2':
                if ($result['payment'] == 1) {
                    $res = $ordermodel->where('id', $result['id'])->update(['status' => 5]);
                    if ($res) {
                        $this->result([], 0, '订单已取消');
                    }
                } else {
                    $res = $ordermodel->where('id', $result['id'])->update(['rece' => 2]);
                    if ($res) {
                        $this->result([], 0, '订单已提交售后');
                    }
                }

                $this->result([], 1, '订单取消失败，请重试');
                break;
            case '3':
                $res = $ordermodel->where('id', $result['id'])->update(['rece' => 2]);
                if ($res) {
                    $this->result([], 0, '订单已提交售后');
                }
                $this->result([], 1, '订单取消失败，请重试');
                break;
            default:
                break;
        }
    }


    public function Ordertrue()
    {
        $ordermodel = new Order();
        $id  = $this->request->post('id/d', 0);
        $result = $ordermodel->where(['user_id' => $this->request->user_id, 'id' => $id])
            ->find();
        if (!$result) {
            $this->result([], 1, '订单不存在');
        }
        if ($result['status'] != 3) {
            $this->result([], 1, '订单状态不可确认');
        }
        Db::startTrans();
        try {
            $ordermodel->order_status($result, 4);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result([], 0, '操作成功');
    }

    public function Orderpay()
    {
        $ordermodel = new Order();
        $id  = $this->request->post('ordersn/d', 0);
        $type  = $this->request->post('type/d', 1);
        $result = $ordermodel->where(['ordersn' => $id])
            ->find();
        if (!$result) {
            $this->result([], 1, '订单不存在');
        }
        if ($result['status'] != 1) {
            $this->result([], 1, '订单状态不可支付');
        }
        switch ($type) {
            case '1':
                //未付款订单直接取消
                if ($result['total'] == 0) {
                    $ispay = 2;
                } else {
                    $ispay = $result['ispay'];
                }
                $shopmodel = new Shoplist();
                $shop = $shopmodel->where('id', $result['shopid'])->find();
                //查询是否可以直接发货
                $admins = Db::name('admin')->where('find_in_set(' . $shop['street'] . ',street)')->where(['type' => [3, 4]])->find();
                if (empty($admins)) {
                    $admins = Db::name('admin')->where('find_in_set(' . $shop['area'] . ',area)')->where(['type' => 2])->find();
                }
                if (empty($admins)) {
                    $order['type'] = 1;
                    $order['aid'] = $result['shopid'];
                } else {
                    $order['type'] = 2;
                    $order['aid'] = $admins['id'];
                }
                $res = $ordermodel->where('id', $result['id'])->update(['status' => 2, 'payment' => 1, 'ispay' => $ispay, 'type' => $order['type'], 'aid' => $order['aid']]);
                if ($res) {
                    $this->result([], 0, '已选择货到付款');
                }
                $this->result([], 1, '操作失败，请重试');
                break;
            case '2':
                $payment = [
                    'pay_title' => '订单编号:' . $result['ordersn'],
                    'payment_id' =>  $result['ordersn'] . rand(1000, 9999),
                    'money' => $result['total'],
                    'ip' => $this->request->ip(),
                    'user_id' => $result['user_id'],
                    'params' => json_encode(['trade_type' => 'JSAPI'], true)
                ];
                $list = (new Wechat())->pay($payment);
                if ($list['status'] == true) {
                    $res = (new Payment())->save([
                        'paymentid' => $payment['payment_id'],
                        'orderid' => $result['id'],
                        'money' => $payment['money']
                    ]);
                    if ($res) {
                        $this->result($list, 0, '获取成功');
                    }
                }
                $this->result([], 1, '操作失败，请重试');
                break;
            default:
                break;
        }
    }

    public function pay()
    {
        $payment = [
            'pay_title' => '订单编号:' . time(),
            'payment_id' =>  time() . rand(1000, 9999),
            'money' => rand(1, 10) / 100,
            'ip' => $this->request->ip(),
            'user_id' => $this->request->user_id,
            'params' => json_encode(['trade_type' => 'JSAPI'], true)
        ];
        $list = (new Wechat())->pay($payment);
        if ($list['status'] == true) {
            $this->result($list, 0, '获取成功');
        }
        $this->result([], 1, '操作失败，请重试');
    }

    //回调结果
    public function callback()
    {
        try {
            //获取通知的数据
            $xml = file_get_contents('php://input');
            //禁止引用外部xml实体
            libxml_disable_entity_loader(true);
            $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            Log::write($data, 'weichats');

            if ($data && $data['return_code'] == 'SUCCESS') {
                //说明值没问题，并且验证签名通过
                if ($data['result_code'] == "SUCCESS") {
                    $payment = (new Payment())->where('paymentid', $data['out_trade_no'])->find();
                    if (!empty($payment)) {
                        //获取订单
                        $order = (new Order())->where(['id' => $payment['orderid'], 'status' => 3])->find();
                        //更新支付订单
                        Db::startTrans();
                        try {
                            (new Payment())->where('paymentid', $data['out_trade_no'])->update(['status' => 2]);
                            //更新订单状态
                            if (!empty($order)) {
                                (new Order())->where(['id' => $order['id']])->update(['status' => 5]);
                                //查询管理员ID
                                $adminid = (new RiderStreet())->where(['riderid' => $order['orders_id'], 'street' => $order['street']])->value('adminid') ?? 0;
                                $admin = (new Admin())->where('id', $adminid)->find();
                                if (!empty($admin)) {
                                    (new Admin())->MoneyEdit($admin['id'], $admin['money'], $order['total'], 1, $order['id'], "订单入账");
                                }
                            }
                            Db::commit();
                        } catch (\Exception $e) {
                            Db::rollback();
                            Log::write('回调失败：' . $e, 'weichats');
                        }
                    }
                } else {
                    //如果未支付成功，也更新支付单
                    (new Payment())->where('paymentid', $data['out_trade_no'])->update(['status' => 3]);
                }
                $result['msg'] = 'success';
            } else {
                $result['msg'] = 'fail';
                return $result;
            }
        } catch (\Throwable $th) {
            Log::write($th, 'weichats');
        }
    }
}